package com.itcast.aop;

import com.itcast.mapper.OperateLogMapper;
import com.itcast.pojo.OperateLog;
import com.itcast.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class LogOperationAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itcast.anno.LogOperationAnnotation)")
    public  Object logOperationInsert(ProceedingJoinPoint joinPoint) throws Throwable {
        //设置开始时间
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();
        //设置结束时间
        long end = System.currentTimeMillis();

        OperateLog olog = new OperateLog();
        //设置操作时间
        olog.setOperateTime(LocalDateTime.now());
        //设置员工Id
        olog.setOperateEmpId(getEmpId());
        //类名
        olog.setClassName(joinPoint.getTarget().getClass().getName());
        //耗时
        olog.setCostTime(end-start);
        //设置操作方法
        olog.setMethodName(joinPoint.getSignature().getName());
        //方法参数
        olog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        //设置返回值
        olog.setReturnValue(result!=null?result.toString():"void");

        operateLogMapper.insert(olog);

        return result;
    }

    private Integer getEmpId() {
        return CurrentHolder.getCurrentId();
    }
}
